package com.milk.servlet;

import com.milk.Dao.MilkTeaDrinksDao;
import com.milk.entity.MilkTeaDrinks;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


public class MilkTeaDrinksServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有饮品
        }

        switch (action) {
            case "/add":
                showAddDrinkForm(request, response);
                break;
            case "/edit":
                showEditDrinkForm(request, response);
                break;
            case "/delete":
                deleteDrink(request, response);
                break;
            case "/search":
                searchDrink(request, response);
                break;
            default:
                listAllDrinks(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 获取操作类型
        String action = request.getPathInfo();
        if (action == null || action.equals("/")) {
            action = "/list"; // 默认操作是列出所有饮品
        }

        switch (action) {
            case "/add":
                addDrink(request, response);
                break;
            case "/update":
                updateDrink(request, response);
                break;
            default:
                // 处理其他不支持的POST请求
                response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }

    private void listAllDrinks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 查询所有奶茶饮品信息
        List<MilkTeaDrinks> drinks = MilkTeaDrinksDao.findAll();
        request.setAttribute("drinks", drinks);

        // 转发到饮品列表页面（假设为drink_management.jsp）
        request.getRequestDispatcher("/drink_management.jsp").forward(request, response);
    }

    private void showAddDrinkForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取输出流对象
        PrintWriter out = response.getWriter();

        // 输出添加饮品表单页面
        out.println("<html><body>");
        out.println("<h3>添加奶茶饮品</h3>");
        out.println("<form action='" + request.getContextPath() + "/drinks/add' method='post'>");
        out.println("<label for='name'>名称</label><input type='text' id='name' name='name' placeholder='请输入奶茶名称'><br>");
        out.println("<label for='category'>分类</label><input type='text' id='category' name='category' placeholder='请输入奶茶分类（默认其他）'><br>");
        out.println("<label for='price'>价格</label><input type='number' id='price' name='price' step='0.01' placeholder='请输入奶茶价格'><br>");
        out.println("<label for='description'>描述</label><textarea id='description' name='description' placeholder='请输入奶茶描述'></textarea><br>");
        out.println("<button type='submit'>添加</button>");
        out.println("</form>");
        out.println("</body></html>");
    }

    private void addDrink(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取饮品信息参数
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        if (category.isEmpty()) {
            category = "其他";
        }
        double price = Double.parseDouble(request.getParameter("price"));
        String description = request.getParameter("description");

        // 创建MilkTeaDrinks对象
        MilkTeaDrinks drink = new MilkTeaDrinks();
        drink.setName(name);
        drink.setCategory(category);
        drink.setPrice(price);
        drink.setDescription(description);

        // 调用MilkTeaDrinksDao的方法添加饮品
        int result = MilkTeaDrinksDao.add(drink);
        if (result > 0) {
            // 添加成功，重定向到饮品列表页面
            response.sendRedirect(request.getContextPath() + "/drinks");
        } else {
            // 添加失败，返回错误信息
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h3>添加失败，请检查输入信息。</h3>");
            out.println("</body></html>");
        }
    }

    private void showEditDrinkForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取输出流对象
        PrintWriter out = response.getWriter();

        // 获取要修改的饮品ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 根据ID查询饮品信息
        MilkTeaDrinks drink = MilkTeaDrinksDao.findById(id);
        if (drink != null) {
            // 输出修改饮品表单页面
            out.println("<html><body>");
            out.println("<h3>修改奶茶饮品</h3>");
            out.println("<form action='" + request.getContextPath() + "/drinks/update' method='post'>");
            out.println("<input type='hidden' name='id' value='" + id + "'>");
            out.println("<label for='name'>名称</label><input type='text' id='name' name='name' placeholder='请输入奶茶名称' value='" + drink.getName() + "'><br>");
            out.println("<label for='category'>分类</label><input type='text' id='category' name='category' placeholder='请输入奶茶分类（默认其他）' value='" + drink.getCategory() + "'><br>");
            out.println("<label for='price'>价格</label><input type='number' id='price' name='price' step='0.01' placeholder='请输入奶茶价格' value='" + drink.getPrice() + "'><br>");
            out.println("<label for='description'>描述</label><textarea id='description' name='description' placeholder='请输入奶茶描述'>" + drink.getDescription() + "</textarea><br>");
            out.println("<input type='submit' value='提交'>");
            out.println("</form>");
            out.println("</body></html>");
        } else {
            // 未找到对应的饮品，返回错误信息
            out.println("<html><body>");
            out.println("<h3>未找到对应的奶茶饮品，请检查输入的ID是否正确。</h3>");
            out.println("</body></html>");
        }
    }

    private void updateDrink(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取饮品信息参数
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String category = request.getParameter("category");
        if (category.isEmpty()) {
            category = "其他";
        }
        double price = Double.parseDouble(request.getParameter("price"));
        String description = request.getParameter("description");

        // 创建MilkTeaDrinks对象
        MilkTeaDrinks drink = new MilkTeaDrinks();
        drink.setId(id);
        drink.setName(name);
        drink.setCategory(category);
        drink.setPrice(price);
        drink.setDescription(description);

        // 调用MilkTeaDrinksDao的方法修改饮品信息
        int result = MilkTeaDrinksDao.update(drink);
        if (result > 0) {
            // 修改成功，重定向到饮品列表页面
            response.sendRedirect(request.getContextPath() + "/drinks");
        } else {
            // 修改失败，返回错误信息
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h3>修改失败，请检查输入信息。</h3>");
            out.println("</body></html>");
        }
    }

    private void deleteDrink(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取要删除的饮品ID
        int id = Integer.parseInt(request.getParameter("id"));

        // 调用MilkTeaDrinksDao的方法删除饮品
        int result = MilkTeaDrinksDao.deleteById(id);
        if (result > 0) {
            // 删除成功，重定向到饮品列表页面
            response.sendRedirect(request.getContextPath() + "/drinks");
        } else {
            // 删除失败，返回错误信息
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h3>删除失败，请检查输入的ID是否正确。</h3>");
            out.println("</body></html>");
        }
    }

    private void searchDrink(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为HTML，并指定字符编码为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        // 获取搜索关键字
        String name = request.getParameter("searchName");

        // 调用MilkTeaDrinksDao的方法进行模糊搜索
        List<MilkTeaDrinks> drinks = MilkTeaDrinksDao.searchByName(name);
        request.setAttribute("drinks", drinks);

        // 转发到饮品列表页面（假设为drink_management.jsp）
        request.getRequestDispatcher("/drink_management.jsp").forward(request, response);
    }
}